package com.pig.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.pig.config.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class Alipay {


    @RequestMapping("/alipay")
    public void pay(@RequestParam String orderId,@RequestParam String payAmount, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        DefaultAlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl,AlipayConfig.app_id,AlipayConfig.merchant_private_key,"json",AlipayConfig.charset,AlipayConfig.alipay_public_key,AlipayConfig.sign_type);
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        Map<String,Object> map=new HashMap<>();
        map.put("out_trade_no",orderId);
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",payAmount);
        map.put("subject","佩奇牧场"+orderId);
        String string = JSONObject.toJSONString(map);
        System.out.println(string);
        log.info("---"+string);
        alipayTradePagePayRequest.setBizContent(string);
        String body = client.pageExecute(alipayTradePagePayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(body);
        response.getWriter().flush();
        response.getWriter().close();

    }


}
